<script setup lang="ts">

import {getCurrentInstance, onMounted, reactive, ref} from "vue";
import {get, post} from "../http";
import FullScreen from "../components/FullScreen.vue";
import play from '../assets/play.svg'
import pause from '../assets/pause.svg'
import {copyProperties, resTip} from "../util/Common";
import PopBox from '../components/popBox.vue';

const {proxy: ins}: any = getCurrentInstance();
let showTip = ref<boolean>(false);
let sign = 0
onMounted(async () => {
  if ((await post(`/member/bind/login?sign=${sign}`, {})).code !== 200) {
    showTip.value = true;
  } else {
    await getLikeSong();
    await getLikeSinger();
  }
})


let likeClass = ref<any>("active");
let singerClass = ref<any>("");

interface LikeSongI {
  id: number,
  songId: number,
  mvId: number,
  url: string,
  musicType: string,
  songName: string,
  picUrl: string,
  fee: string,
  isPlay: boolean
}

interface LikeSingerI {
  id: number,
  name: string,
  img1v1Url: string,
}

let songList = reactive<Array<LikeSongI>>([]);
let likeSinger = reactive<Array<LikeSingerI>>([]);
let currentSong = ref<string>('');
let likePage = ref<boolean>(true);

function goLike() {
  likeClass.value = 'active'
  singerClass.value = ''
  likePage.value = true;
  getLikeSong();
}

function goSinger() {
  singerClass.value = 'active'
  likeClass.value = ''
  likePage.value = false;
}

async function getLikeSong() {
  let res = await get('/music/like/songs?pageSize=99999&pageNum=1');
  if (res.code === 200) {
    songList.length = 0;
    res.data.records.forEach((item: LikeSongI) => {
      songList.push(item)
    })
  } else {
    //获取失败就会重新调用登陆接口，也就是cookie失效了
    sign = 1;
    await post(`/member/bind/login?sign=${sign}`, {})
  }
}

async function getLikeSinger() {
  let res = await get('/music/collect/Singers');
  if (res.code === 200) {
    likeSinger.length = 0;
    res.data.forEach((item: LikeSingerI) => likeSinger.push(item));
  }
  console.log(res)
}

let lastPlayRow: any;
let lastPlayType: any;
let audioRef = ref<HTMLAudioElement>();

async function playMusic(songId: number, rowIndex: number, type = 0) {
  if (lastPlayRow === rowIndex && lastPlayType === type && audioRef.value) {
    if (audioRef.value.paused) {
      audioRef.value.play();
      if (type === 0) {
        songList[lastPlayRow].isPlay = true;
      } else {
        singerDetailInfo.songs[lastPlayRow].isPlay = true;
      }
    } else {
      audioRef.value.pause();
      if (type === 0) {
        songList[lastPlayRow].isPlay = false;
      } else {
        singerDetailInfo.songs[lastPlayRow].isPlay = false;
      }
    }
    return;
  }
  let res = await get(`/music/song/url?id=${songId}`);
  if (res.code === 200) {
    currentSong.value = res.data.data[0].url
    if (lastPlayRow !== undefined) {
      if (lastPlayType === 0) {
        songList[lastPlayRow].isPlay = false;
      } else {
        singerDetailInfo.songs[lastPlayRow].isPlay = false;
      }
    }
    if (type === 0) {
      songList[rowIndex].isPlay = true;
    } else {
      singerDetailInfo.songs[rowIndex].isPlay = true;
    }
    lastPlayRow = rowIndex;
    lastPlayType = type;
  }
}

async function synchronize() {
  resTip(ins, await get('music/synchronous'), () => getLikeSong())
}

let searchContent = ref<string>();

async function doSearch() {
  if (searchContent) {
    let res = await get(`/music/public/search?keywords=${searchContent.value}`);
    if (res.code === 200) {
      songList.length = 0;
      for (const song of res.data.result.songs) {
        songList.push({
          id: 0,
          songId: song.id,
          mvId: song.mv,
          url: '',
          musicType: '网易云',
          songName: song.name,
          picUrl: song.al.picUrl,
          fee: song.fee,
          isPlay: false
        });
      }
      singerClass.value = ''
      likeClass.value = ''
      likePage.value = true;
    }
  }
}


let singerStartX = ref(0);
let singerStartY = ref(0);

interface SingerDetailI {
  id: number,
  musicSize: string,
  mvSize: number,
  name: number,
  description: string,
  picUrl: string,
  songs: Array<LikeSongI>
}

let singerDetailInfo = reactive<SingerDetailI>({
  id: 0,
  musicSize: '',
  mvSize: 0,
  name: 0,
  description: '',
  picUrl: '',
  songs: []
});

async function singerDetail(id: number, event: PointerEvent) {
  singerStartX.value = event.clientX;
  singerStartX.value = event.clientY;
  let res = await get(`/music/singer/detail?id=${id}`);
  if (res.code === 200) {
    copyProperties(res.data, singerDetailInfo);
    console.log(singerDetailInfo)
  }
}


let mvStartX = ref(0);
let mvStartY = ref(0);
let mvUrl = ref();

async function playMv(mvId: number, event: PointerEvent) {
  mvStartX.value = event.clientX;
  mvStartY.value = event.clientY;
  let res = await get(`/music/mv/detail?id=${mvId}`)
  if (res.code === 200) {
    mvUrl.value = res.data.url;
  }
}

let commentStartX = ref(0);
let commentStartY = ref(0);

interface CommentInfoI {
  content: string,
  commentTime: string,
  nickname: string,
  avatarUrl: string,
}

let commentInfo = reactive<Array<CommentInfoI>>([]);

async function getComment(songId: number, event: PointerEvent) {
  commentStartX.value = event.clientX;
  commentStartY.value = event.clientY;
  commentInfo.length = 0;
  let res = await get(`/music/comment/song?id=${songId}&limit=100`)
  if (res.code === 200) {
    res.data.forEach((comment: any) => {
      commentInfo.push({
        content: comment.content,
        commentTime: comment.commentTime,
        nickname: comment.user.nickname,
        avatarUrl: comment.user.avatarUrl,
      })
    })
  }
}

async function likeSong(songId:number,like:boolean){
  resTip(ins,await get(`music/song/like?id=${songId}&like=${like}`))
}

</script>

<template>
  <div class="music-main">
    <div class="header">
      <div class="tap-container">
        <span class="tap" :class="likeClass" @click="goLike">我喜欢</span>
        <span class="tap" :class="singerClass" @click="goSinger">歌手</span>
      </div>
      <div class="search">
        <audio
            ref="audioRef"
            :src="currentSong"
            autoplay
            controls="controls">
          Your browser does not support the audio element.
        </audio>
        <el-input v-model="searchContent"></el-input>
        <el-button @click="doSearch">搜索</el-button>
        <el-button @click="synchronize">同步</el-button>
      </div>
    </div>
    <div v-if="likePage" class="like-song">
      <el-table :data="songList" style="width: 100%">
        <el-table-column label="封面" width="200">
          <template #default="scope">
            <div class="img" @click="playMusic(scope.row.songId,scope.$index)">
              <img class="cover" :src="scope.row.picUrl" alt="">
              <img class="play" :src="!scope.row.isPlay?play:pause" alt="">
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="songName" label="名称"/>
        <el-table-column prop="musicType" label="来自"/>
        <el-table-column label="类别">
          <template #default="scope">
            <span>{{
                scope.row.fee === 0 ? '免费歌曲' : scope.row.fee === 1 ? 'VIP歌曲(试听30秒)' : scope.row.fee === 4 ? '需要购买专辑' : '低音质歌曲'
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="MV">
          <template #default="scope">
            <span v-if="scope.row.mvId===0">无MV</span>
            <img @click="playMv(scope.row.mvId,$event)" v-if="scope.row.mvId!==0" style="width: 40px;cursor: pointer"
                 :src="play" alt="">
          </template>
        </el-table-column>
        <el-table-column label="评论">
          <template #default="scope">
            <img @click="getComment(scope.row.songId,$event)" style="width: 40px;cursor: pointer"
                 src="../assets/comment.svg" alt="">
          </template>
        </el-table-column>
        <el-table-column label="喜欢/不喜欢">
          <template #default="scope">
            <img @click="likeSong(scope.row.songId,false)" style="width: 40px;cursor: pointer" src="../assets/like.svg" alt="">
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="!likePage" class="singer">
      <div class="item" v-for="item in likeSinger">
        <img :src="item.img1v1Url" alt="" @click="singerDetail(item.id,$event)">
        <p @click="singerDetail(item.id,$event)">{{ item.name }}</p>
      </div>
    </div>
    <teleport to="body">
      <full-screen opacity="0.8" v-if="showTip">
        <div class="not-bind">
          <h1>未绑定音乐账户！</h1>
          <p @click="$router.push('/index/user?activeName=forth')">去绑定</p>
        </div>
      </full-screen>
      <pop-box :start-x="singerStartX" :start-y="singerStartY" size="Huge">
        <div class="singer-detail">
          <div class="upper">
            <img :src="singerDetailInfo.picUrl" alt="">
            <div class="singer-info">
              <h1>{{ singerDetailInfo.name }}</h1>
              <h2>Eason Chan|许嵩|ABC</h2>
              <div class="info-count">
                <span>单曲数量:{{ singerDetailInfo.musicSize }}</span>
                <span>MV数量:{{ singerDetailInfo.mvSize }}</span>
              </div>
              <div class="description">
                <p>描述:</p>
                <p>{{ singerDetailInfo.description }}</p>
              </div>
            </div>
          </div>
          <div class="down">
            <el-table :data="singerDetailInfo.songs" style="width: 100%;border-radius: 10px">
              <el-table-column label="封面" width="150">
                <template #default="scope">
                  <div class="img" @click="playMusic(scope.row.songId,scope.$index,1)">
                    <img class="cover" :src="scope.row.picUrl" alt="">
                    <img class="play" :src="!scope.row.isPlay?play:pause" alt="">
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="songName" label="名称"/>
              <el-table-column prop="musicType" label="来自"/>
              <el-table-column label="类别">
                <template #default="scope">
            <span>{{
                scope.row.fee === 0 ? '免费歌曲' : scope.row.fee === 1 ? 'VIP歌曲(试听30秒)' : scope.row.fee === 4 ? '需要购买专辑' : '低音质歌曲'
              }}</span>
                </template>
              </el-table-column>
              <el-table-column label="喜欢">
                <template #default="scope">
                  <img @click="likeSong(scope.row.songId,true)" style="width: 40px;cursor: pointer" src="../assets/like.svg" alt="">
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </pop-box>

      <pop-box :start-x="mvStartX" :start-y="mvStartY" size="Huge">
        <div style="width: 100%;height: 800px;display: flex;align-items: center">
          <video style="width: 100%; z-index: 999;" :src="mvUrl" controls autoplay></video>
        </div>
      </pop-box>

      <pop-box :start-x="commentStartX" :start-y="commentStartY" size="Huge">
        <div class="comment">
          <el-card v-for="item in commentInfo">
            <div class="comment-item">
              <img :src="item.avatarUrl" alt="">
              <div class="msg">
                <p class="name">{{ item.nickname }}</p>
                <p class="content">{{ item.content }}。</p>
                <p class="time">{{ item.commentTime }}</p>
              </div>
            </div>
          </el-card>
        </div>
      </pop-box>
    </teleport>
  </div>
</template>

<style lang="scss" scoped>

.music-main {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 52px;
    z-index: 99;
    background-color: white;

    .tap-container {
      display: flex;
      align-items: center;
      text-align: center;

      .tap {
        height: 42PX;
        cursor: pointer;
        width: 100px;
        line-height: 42px;
        transition: all .3s ease;
        color: #606266;

        &:hover {
          color: #ff0000;
        }
      }

      .tap.active {
        color: #ff0000;
      }
    }


    .search {
      display: flex;
      align-items: center;

      .el-button {
        height: 42PX;
      }

      audio {
        width: 350px;
        border: none;
      }

      .el-input {
        width: 300px;
      }

      :deep(.el-input__inner) {
        height: 42PX;
      }
    }

  }

  .like-song {

    .img {
      position: relative;
      cursor: pointer;

      .cover {
        width: 100%;
      }

      .play {
        width: 45%;
        position: absolute;
        z-index: 9999;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        transition: all .3s;
        opacity: 0;
      }

      &:hover {
        .play {
          opacity: 1;
        }
      }
    }
  }

  .singer {
    margin-top: 20px;
    margin-left: 80px;
    margin-right: 80px;
    display: flex;
    flex-wrap: wrap;

    .item {
      width: 250px;
      margin: 10px 20px;
      padding: 30px;

      img {
        border-radius: 50%;
        width: 100%;
        cursor: pointer;
        user-select: none;
      }

      p {
        text-align: center;
        font-size: 30px;
        user-select: none;
        cursor: pointer;

        &:hover {
          color: #0b9aff;
        }
      }
    }
  }
}

.not-bind {
  color: #e89c9c;
  user-select: none;
  margin-bottom: 300px;

  p {
    text-align: end;
    margin-bottom: 300px;
    color: #1884f1;

    &:hover {
      cursor: pointer;
      text-decoration: underline;
    }
  }
}

.singer-detail {

  .upper {
    padding: 30px;
    display: flex;
    height: 310px;
    overflow: hidden;

    img {
      height: auto;
      width: auto;
      max-width: 250px;
      max-height: 250px;

      border-radius: 10px;
    }

    .singer-info {
      margin-left: 30px;
      overflow: auto;

      h1 {
        font-size: 30px;
      }

      h2 {
        font-size: 20px;
        margin-bottom: 20px;
      }

      .info-count {
        margin-bottom: 20px;

        span {
          font-size: 15px;
          color: #868686;
          margin-right: 20px;
        }
      }

      .description {

      }
    }
  }

  .down {
    overflow: auto;
    height: 500px;

    .img {

      position: relative;
      cursor: pointer;

      .cover {
        width: 50px;
      }

      .play {
        width: 45%;
        position: absolute;
        z-index: 9999;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        transition: all .3s;
        opacity: 0;
      }

      &:hover {
        .play {
          opacity: 1;
        }
      }
    }
  }
}

.comment {
  padding: 50px;
  height: 800px;
  overflow: auto;

  .el-card {
    margin-bottom: 20px;

  }

  .comment-item {
    display: flex;
    margin: 20px;

    img {
      width: 100px;
      height: 100px;
      object-fit: cover;
      border-radius: 100%;
      margin-right: 50px;
    }

    .msg {
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .name {
        color: #0b9aff;
      }

      .content {
        margin-bottom: 20px;
      }

      .time {
        font-size: 10px;
        color: #8f8f8f;
      }
    }
  }
}
</style>
